package com.firefly.app.biz.alipay;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import android.app.Activity;

import com.firefly.app.cordova.dto.SytPayResult;
import com.firefly.app.cordova.enums.SytPayEnum;
import com.firefly.mobile.app.config.Config;

public class PayDemoUtil{
	
	/**
	 * 终端设备是否存在支付宝认证账户
	 */
	public  static boolean isExsit = false;

	// 商户PID
	public static final String PARTNER = "2088221474266226";
	// 商户收款账号
	public static final String SELLER = "info@winhc.cn";
	// 商户私钥，pkcs8格式
	public static final String RSA_PRIVATE = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAL+VCzHyHKwslAlYEcQNjZs4ywicRnXCKlwblw1RacdipbQjqOxqRDf+aVHjhCpxOiDcfLkY4x6GVUMST+0m98mOhxjVY1Us4xUuUt8WESgiH7dOIJfFCHFAyijkXQbSvctOSC4oeyMcFoHCoLebi0ZXpy7bwjYTKbqD54Tw3GgHAgMBAAECgYB7wO0wYDMBTPJ7brZbLF4SrIcKktg47Smrwe67HaH0t9ZOHNLblHFosiCaUxtmxylDXOn8LwVXDHM7FjMnAAsCusSaPU2LZ/PIulLiXGmzRuU1YPZSCccxkmwxcfOrJdwwS6aLm5imcgcnwARjk3DOd4SJ+acWY6BxfIAG7yAh0QJBAPCUiPs3CWxyNl/b+JD6UURP8n3nnydfIdUeL/zBhD6N3xijErsaQ0KAS5Rvp8rxpptWdR3bEHnrIoJ3XKC+fI0CQQDL3ItRRFKvTuSyHiX7oAPE264WT5HA1hM930C+dLeOAtJ2Nhkas0KxSn2XFauv60LTQ6SAyLSMhCpgkA2165PjAkBIWKKIyRgwYHgxg3jQQDZIELKfYhPeRyFpcVaE77zRAuDgC8oKMe+gA+y2io0u3lR3yhwWClZ+E1OhYDueqynRAkA2ImOQef8m9GFAd0cI0Y4OqXNKE2kV9wL3DCDKMn5HpLI0l9sEvxN3ttsw0p1bwrJlHXJCjIl9Qt9p8vbhFySXAkB6lcR2kILVhXoBeHVj1aQw+0OKIgx82MZ3YdEl2G3xMx53ukKw14tcDiUuo+Ztbi4ptKDBFm+6/FZAsg42JL6i";
	// 支付宝公钥
	public static final String RSA_PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnxj/9qwVfgoUh/y2W89L6BkRAFljhNhgPdyPuBV64bfQNN1PjbCzkIM6qRdKBoLPXmKKMiFYnkd6rAoprih3/PrQEB/VsW8OoM8fxn67UDYuyBTqA23MML9q1+ilIZwBC2AQ2UBVOrFXfFl75p6/B5KsiNG9zpgmLCUYuLkxpLQIDAQAB";

	//我们自己的url
//	public static final String NOTIFY_URL = "http://101.231.249.230:8924/alipay-proxy/alipayNotifyByMobileApp";
	
	private static String NOTIFY_URL = Config.getString("alipay.proxy.notifyUrlByMobileApp");
	
	
	private static final int SDK_PAY_FLAG = 1;

	private static final int SDK_CHECK_FLAG = 2;


	/**
	 * call alipay sdk pay. 调用SDK支付
	 * 
	 */
	public static SytPayResult  pay(AlipayOrderInfo alipayOrderInfo,final Activity v) {
		SytPayResult sytPayResult = new SytPayResult();
		check(v);
		if (!isExsit) {
			sytPayResult.setCode(SytPayEnum.未安装.getCode());
			sytPayResult.setMsg(SytPayEnum.未安装.getDesc());
			return sytPayResult;
		}
		// 订单
		String orderInfo = getOrderInfo(alipayOrderInfo);

		// 对订单做RSA 签名
		String sign = sign(orderInfo);
		try {
			// 仅需对sign 做URL编码
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		// 完整的符合支付宝参数规范的订单信息
		final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
				+ getSignType();
		final LinkedBlockingQueue<Boolean> checkQueue = new LinkedBlockingQueue<Boolean>();
		Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
//				// 构造PayTask 对象
//				PayTask alipay = new PayTask(v);
//				// 调用支付接口，获取支付结果
//				String result = alipay.pay(payInfo);
//				Log.i("ytgAlipay", "支付回调结果"+result);
//				if (result!= null && result.indexOf("resultStatus={9000}") >= 0 ) {
//					FireflyMobileActivity.sendMsgToSytActivity("jsExec|window.location.href = '../home/index.html#/sucRepaying'");
//				}else if (result!= null && result.indexOf("resultStatus={4000}") >= 0 ) {
//					try {
//						checkQueue.put(false);
//					} catch (InterruptedException e) {
//						e.printStackTrace();
//					}
//				}
			}
		};

		// 必须异步调用
		Thread payThread = new Thread(payRunnable);
		payThread.start();
		
		try {
			if (!checkQueue.poll(1L, TimeUnit.SECONDS)) {
				sytPayResult.setCode(SytPayEnum.未安装.getCode());
				sytPayResult.setMsg(SytPayEnum.未安装.getDesc());
				return sytPayResult;
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		sytPayResult.setCode(SytPayEnum.成功.getCode());
		sytPayResult.setMsg(SytPayEnum.成功.getDesc());
		return sytPayResult;
	}

	/**
	 * check whether the device has authentication alipay account.
	 * 查询终端设备是否存在支付宝认证账户
	 * 
	 */
	public static void check(final Activity v) {
	    /**
	     * 消息队列
	     */
	   final LinkedBlockingQueue<Boolean> checkQueue = new LinkedBlockingQueue<Boolean>();
	    
		Runnable checkRunnable = new Runnable() {

			@Override
			public void run() {
//				// 构造PayTask 对象
//				PayTask payTask = new PayTask(v);
//				// 调用查询接口，获取查询结果
//				boolean isExist = payTask.checkAccountIfExist();
//				SytLog.i("查询终端设备是否存在支付宝认证账户"+isExist);
//				try {
//					checkQueue.put(isExist);
//				} catch (InterruptedException e) {
//					e.printStackTrace();
//				}
			}
		};

		Thread checkThread = new Thread(checkRunnable);
		checkThread.start();
		try {
			isExsit = checkQueue.poll(3L, TimeUnit.SECONDS);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	/**
	 * get the sdk version. 获取SDK版本号
	 * 
	 */
	public void getSDKVersion(Activity v) {
//		PayTask payTask = new PayTask(v);
//		String version = payTask.getVersion();
	}

	/**
	 * create the order info. 创建订单信息
	 * 
	 */
	public static String getOrderInfo(AlipayOrderInfo alipayOrderInfo) {

		// 签约合作者身份ID
		String orderInfo = "partner=" + "\"" + PARTNER + "\"";

		// 签约卖家支付宝账号
		orderInfo += "&seller_id=" + "\"" + SELLER + "\"";

		// 商户网站唯一订单号
		orderInfo += "&out_trade_no=" + "\"" + alipayOrderInfo.getOutTradeNo() + "\"";

		// 商品名称
		orderInfo += "&subject=" + "\"" + alipayOrderInfo.getSubject() + "\"";

		// 商品详情
		orderInfo += "&body=" + "\"" + alipayOrderInfo.getBody() + "\"";

		// 商品金额
		orderInfo += "&total_fee=" + "\"" + alipayOrderInfo.getTotalFee() + "\"";

		// 服务器异步通知页面路径
		orderInfo += "&notify_url=" + "\"" + NOTIFY_URL
				+ "\"";

		// 服务接口名称， 固定值
		orderInfo += "&service=\"mobile.securitypay.pay\"";

		// 支付类型， 固定值
		orderInfo += "&payment_type=\"1\"";

		// 参数编码， 固定值
		orderInfo += "&_input_charset=\"utf-8\"";

		// 设置未付款交易的超时时间
		// 默认30分钟，一旦超时，该笔交易就会自动被关闭。
		// 取值范围：1m～15d。
		// m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
		// 该参数数值不接受小数点，如1.5h，可转换为90m。
		orderInfo += "&it_b_pay=\"30m\"";

		// extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
		// orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

		// 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
		orderInfo += "&return_url=\"m.alipay.com\"";

		// 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
		// orderInfo += "&paymethod=\"expressGateway\"";

		return orderInfo;
	}

	/**
	 * get the out_trade_no for an order. 生成商户订单号，该值在商户端应保持唯一（可自定义格式规范）
	 * 
	 */
	public String getOutTradeNo() {
		SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss",
				Locale.getDefault());
		Date date = new Date();
		String key = format.format(date);

		Random r = new Random();
		key = key + r.nextInt();
		key = key.substring(0, 15);
		return key;
	}

	/**
	 * sign the order info. 对订单信息进行签名
	 * 
	 * @param content
	 *            待签名订单信息
	 */
	public static String sign(String content) {
		return SignUtils.sign(content, RSA_PRIVATE);
	}

	/**
	 * get the sign type we use. 获取签名方式
	 * 
	 */
	public static String getSignType() {
		return "sign_type=\"RSA\"";
	}

}
